/**
 * 
 */
package com.vision.core.sv.serv.rpc.handler;

import java.util.List;

import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.DispatchException;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.stereotype.Component;

import com.vision.core.cm.action.GetActivityLogsAction;
import com.vision.core.cm.action.GetActivityLogsResult;
import com.vision.core.cm.data.Domain;
import com.vision.core.cm.db.data.ActivityLog;
import com.vision.core.sv.db.mgr.ISimpleCriteria;
import com.vision.core.sv.db.mgr.SimpleCriteria;
import com.vision.core.sv.serv.dispatch.BaseActionHandler;

/**
 * @author Mark
 *
 */
@Component
public class GetActivityLogsHandler extends BaseActionHandler<ActivityLog<?>, GetActivityLogsAction, GetActivityLogsResult> {

	@Override
	public Class<GetActivityLogsAction> getActionType() {
		return GetActivityLogsAction.class;
	}
	
	@Override
	protected Domain getDomain() {
		return Domain.ACTIVITY_LOG;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public GetActivityLogsResult execute(GetActivityLogsAction action, ExecutionContext context) throws DispatchException {
		String query = "SELECT * FROM activity_log ORDER BY timestamp DESC OFFSET ? LIMIT ?";
		
		Session session = activityLogManager.openSession();
			// Get the logs
			SQLQuery selectSql = session.createSQLQuery(query);
			selectSql.addEntity(ActivityLog.class);
			selectSql.setLong(0, action.getOffset());
			selectSql.setLong(1, action.getLimit());
			List<ActivityLog<?>> list = selectSql.list();
		session.close();
		
		// Count the actual size
		ISimpleCriteria countCrit = SimpleCriteria.forClass(ActivityLog.class);
		countCrit.count();
		Long count = (Long) activityLogManager.getTemplate().findByCriteria(countCrit.getDetached()).get(0);
		
		GetActivityLogsResult result = new GetActivityLogsResult(list, action.getOffset());
		result.setTotalLength(count.intValue());
		return result;
	}
	
}
